<?php 

require_once('../shared/connect.php');

$current_time = time();

$id_list = json_decode($_POST[id]);

$assoc_id_list = json_decode($_POST[assoc_id]);

$has_location = count($id_list) > 0;

if ($has_location) {

	// delete the location arrived at
	$sql = "DELETE FROM location 
			WHERE id IN (".implode(", ", $id_list).")
	";

	
	$delete = mysql_query($sql) or die(mysql_error());

	// remove associations with the deleted location
	$sql = "UPDATE location SET assoc_id = NULL 
			WHERE assoc_id IN (".implode(", ", $id_list).")";
	
	$update = mysql_query($sql) or die(mysql_error());

	// search for van entry
	$sql = "SELECT * FROM location WHERE type = 'VAN'";
	$read = mysql_query($sql) or die(mysql_error());

	if ($row = mysql_fetch_assoc($read)) { 
		// got van entry; update its location, size, etc
		$sql = "UPDATE location 
				SET 
					address = '$_POST[address]', 
					num_people = num_people + $_POST[num_people],
					last_updated = '$current_time'
				WHERE id = '$row[id]'";
	} else {
		// no van entry, so make it
		$sql = "INSERT INTO location (assoc_id, van, type, address, num_people, 
									  total_wait, start_time, last_updated)
							VALUES (NULL, '$_POST[van]', 'VAN', '$_POST[address]',
									'$_POST[num_people]', '$_POST[total_wait]', 
									'$current_time', '$current_time')";
	}

	$update = mysql_query($sql) or die(mysql_error());
}

touch('last_updated');

?>